package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1.校验参数
        dto.checkParam();
        //2.执行查询
        //2.1分页条件
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //2.2查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.lambdaQuery();
        if (dto.getStatus() != null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //2.3执行查询
        IPage<ApUserRealname> pageResult = this.page(pageReq, queryWrapper);
        //3.封装结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }

    @Autowired
    private ApUserMapper apUserMapper;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验信息
        if (dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证id不能为空");
        }
        //  根据实名认证的id 查询实名认证信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //  判断实名认证的状态是否为待审核 （1 2 9 ）
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证不是待审核状态");
        }
        //  根据实名认证关联的userId 查询出apUser对象的信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未发现该实名认证关联的apUser信息");
        }
        //TODO 审核通过，进行AI校验实名认证信息的有效性
        if(AdminConstants.PASS_AUTH.equals(status)){
            //1.根据身份证正面照片 OCR 扫描出 姓名+身份证号
            //2.根据姓名+身份证号调用公安部接口判断真实性（为假将状态改为2）
            //3.调用活体检测接口检测liveImage是否为真实自拍 score > 85 即为真（为假将状态改为2）
            //4.使用人证核验接口判断活体检测照片和身份证上的照片是否为同一个人 score > 85 即为真（为假将状态改为2）
        }

        //2.修改实名认证的状态
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMsg());
        this.updateById(apUserRealname);
        //3.如果状态为9的操作
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //  开通自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //  创建作者信息
            createAuthor(wmUser,apUser);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 远程创建作者信息
     * @param wmUser
     * @param apUser
     */
    private void createAuthor(WmUser wmUser, ApUser apUser) {
        //1.根据ApUserId远程查询作者信息
        ResponseResult<ApAuthor> authResult = articleFeign.findByUserId(apUser.getId());
        if (!authResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");
        }
        //2.判断作者信息是否存在
        ApAuthor apAuthor = authResult.getData();
        if (apAuthor != null){
            //3.存在，返回创建失败
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者已存在，创建失败");
        }
        //4.不存在，创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //5.远程保存作者信息
        articleFeign.save(apAuthor);
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    /**
     * 远程开通自媒体账户
     * @param dto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1.根据用户名 远程查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");
        }
        WmUser wmUser = result.getData();

        //2.如果有该用户 抛出异常
        if (wmUser != null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体账户已存在，开通失败");
        }
        //3.如果没有该用户 则创建一个新的自媒体用户
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //4.远程保存自媒体用户
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");
        }
        return saveResult.getData();
    }
}
